import prisma from '@/lib/prisma'
import { readdir, stat } from 'fs/promises'
import path from 'path'
import { existsSync } from 'fs'
import { PLAN_LIMITS, LimitType, PlanType } from '@/lib/planConfig'

// 计算用户文件夹的实际存储使用量
export async function calculateUserStorageUsage(userId: string): Promise<number> {
  const userDir = path.join(process.cwd(), 'uploads', 'users', userId)
  
  if (!existsSync(userDir)) {
    return 0
  }
  
  async function getDirectorySize(dirPath: string): Promise<number> {
    let totalSize = 0
    
    try {
      const items = await readdir(dirPath)
      
      for (const item of items) {
        const itemPath = path.join(dirPath, item)
        const stats = await stat(itemPath)
        
        if (stats.isDirectory()) {
          totalSize += await getDirectorySize(itemPath)
        } else {
          totalSize += stats.size
        }
      }
    } catch (error) {
      console.error(`读取目录失败: ${dirPath}`, error)
    }
    
    return totalSize
  }
  
  const totalBytes = await getDirectorySize(userDir)
  // 转换为 MB
  return Math.ceil(totalBytes / (1024 * 1024))
}

export async function resetToFreeUser(userId: string) {
  const freeLimits = PLAN_LIMITS.free
  await prisma.vms_user.update({
    where: { id: userId },
    data: {
      plan_type: 'free',
      plan_end_date: null,
      // 添加清除vip相关字段
      vip_type: null,
      vip_end_time: null,
      ...Object.fromEntries(
        Object.entries(freeLimits).map(([key, value]) => [key, value])
      )
    }
  })
}

export async function resetMonthlyUsage(userId: string) {
  const nextMonth = new Date()
  nextMonth.setMonth(nextMonth.getMonth() + 1)
  nextMonth.setDate(1)
  nextMonth.setHours(0, 0, 0, 0)

  await prisma.vms_user.update({
    where: { id: userId },
    data: {
      ai_count: 0,
      voice_count: 0,
      copy_count: 0,
      topic_count: 0,
      script_count: 0,
      subtitle_count: 0,
      monthly_reset_date: nextMonth
    }
  })
}

export async function checkUserLimit(
  userId: string, 
  limitType: LimitType
): Promise<{ allowed: boolean; currentCount: number; limit: number; planType: string }> {
  const user = await prisma.vms_user.findUnique({
    where: { id: userId },
    select: {
      ai_count: true,
      ai_count_limit: true,
      voice_count: true,
      voice_count_limit: true,
      copy_count: true,
      copy_count_limit: true,
      topic_count: true,
      topic_count_limit: true,
      script_count: true,
      script_count_limit: true,
      subtitle_count: true,
      subtitle_count_limit: true,
      plan_type: true,
      plan_end_date: true,
      monthly_reset_date: true
    }
  })

  if (!user) {
    throw new Error('用户不存在')
  }

  // 检查套餐是否过期
  const now = new Date()
  if (user.plan_end_date && now > user.plan_end_date) {
    await resetToFreeUser(userId)
    user.plan_type = 'free'
  }

  // 检查是否需要重置月度计数
  if (user.monthly_reset_date && now > user.monthly_reset_date) {
    await resetMonthlyUsage(userId)
  }

  const currentCount = (user as any)[limitType] || 0
  const limit = (user as any)[`${limitType}_limit`] || PLAN_LIMITS[user.plan_type as PlanType]?.[`${limitType}_limit`] || 0

  // -1 表示无限制
  const allowed = limit === -1 || currentCount < limit

  return {
    allowed,
    currentCount,
    limit,
    planType: user.plan_type || 'free'
  }
}

export async function incrementUserCount(
  userId: string,
  limitType: LimitType
) {
  await prisma.vms_user.update({
    where: { id: userId },
    data: {
      [limitType]: {
        increment: 1
      }
    }
  })
}

export async function upgradePlan(userId: string, planType: PlanType, durationMonths: number = 1) {
  const now = new Date()
  const endDate = new Date(now)
  endDate.setMonth(endDate.getMonth() + durationMonths)

  const planLimits = PLAN_LIMITS[planType]
  
  await prisma.vms_user.update({
    where: { id: userId },
    data: {
      plan_type: planType,
      plan_start_date: now,
      plan_end_date: endDate,
      // 添加vip相关字段
      vip_type: planType === 'free' ? null : planType,
      vip_end_time: planType === 'free' ? null : endDate,
      ...Object.fromEntries(
        Object.entries(planLimits).map(([key, value]) => [key, value])
      )
    }
  })
}

// 新增存储检查函数
// 修改 checkStorageLimit 函数
export async function checkStorageLimit(
  userId: string,
  fileSizeBytes: number
): Promise<{ allowed: boolean; currentUsage: number; limit: number; planType: string; remainingBytes: number }> {
  const user = await prisma.vms_user.findUnique({
    where: { id: userId },
    select: {
      plan_type: true,
      plan_end_date: true
    }
  })

  if (!user) {
    throw new Error('用户不存在')
  }

  // 检查套餐是否过期
  const now = new Date()
  const isExpired = user.plan_end_date && user.plan_end_date < now
  const currentPlan = isExpired ? 'free' : (user.plan_type || 'free')

  const currentUsage = await calculateUserStorageUsage(userId)
  
  const currentUsageMB = await calculateUserStorageUsage(userId)
  const currentUsageBytes = currentUsageMB * 1024 * 1024
  
  // 直接从配置文件获取存储限制，移除对user.storage_limit的依赖
  const limitBytes = (PLAN_LIMITS[currentPlan as PlanType]?.storage_limit || 100) * 1024 * 1024 // 转换为字节
  
  // -1 表示无限制
  const allowed = limitBytes === -1 || (currentUsageBytes + fileSizeBytes) <= limitBytes
  const remainingBytes = limitBytes === -1 ? -1 : Math.max(0, limitBytes - currentUsageBytes)

  return {
    allowed,
    currentUsage: currentUsageMB, // 返回MB
    limit: limitBytes === -1 ? -1 : Math.ceil(limitBytes / (1024 * 1024)), // 返回MB
    planType: currentPlan,
    remainingBytes
  }
}

// 更新用户存储使用量（现在只是一个占位函数，实际使用量通过文件系统计算）
export async function updateStorageUsage(
  userId: string,
  fileSizeBytes: number
) {
  // 由于现在直接从文件系统计算存储使用量，这个函数可以保留为空
  // 或者用于记录日志等其他用途
  console.log(`用户 ${userId} 上传了 ${Math.ceil(fileSizeBytes / (1024 * 1024))} MB 的文件`)
}

// 减少用户存储使用量（现在只是一个占位函数，实际使用量通过文件系统计算）
export async function decreaseStorageUsage(
  userId: string,
  fileSizeBytes: number
) {
  // 由于现在直接从文件系统计算存储使用量，这个函数可以保留为空
  // 或者用于记录日志等其他用途
  console.log(`用户 ${userId} 删除了 ${Math.ceil(fileSizeBytes / (1024 * 1024))} MB 的文件`)
}